package com.learning.js_work1;

import jakarta.servlet.*;
import jakarta.servlet.annotation.WebListener;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSessionEvent;
import jakarta.servlet.http.HttpSessionListener;

import java.time.Duration;
import java.time.Instant;
import java.time.LocalDateTime;

@WebListener
public class MyListener implements ServletRequestListener {


    @Override
    public void requestInitialized(ServletRequestEvent sre) {
        System.out.println("myListener监听到request的对象创建");
        ServletRequest servletRequest = sre.getServletRequest();
        System.out.println("========记录访问日志======");


        //请求时间
        System.out.println("请求时间="+ LocalDateTime.now());
        System.out.println("========================");
        //请求的ip
        System.out.println("访问IP="+servletRequest.getRemoteAddr());
        System.out.println("========================");
        //请求方法
        HttpServletRequest httpServletRequest= (HttpServletRequest) sre.getServletRequest();
        String method = httpServletRequest.getMethod();
        System.out.println("请求方法="+method);
        System.out.println("========================");
        //请求URL
        System.out.println("访问的资源URL="+((HttpServletRequest)servletRequest).getRequestURL());
        System.out.println("========================");
        //请求的查询的字符串并记录
        String queryString = httpServletRequest.getQueryString();
        System.out.println("请求字符串="+queryString);
        System.out.println("========================");
        //  User-Agent
        String userAgent = httpServletRequest.getHeader("User-Agent");
        System.out.println("User-Agent: " + userAgent);
        System.out.println("========================");

        //请求开始记录时间
        sre.getServletRequest().setAttribute("requestStartTime", Instant.now());





    }
    @Override
    public void requestDestroyed(ServletRequestEvent sre) {
        Instant startTime= (Instant) sre.getServletRequest().getAttribute("requestStartTime");
        Instant endTime=Instant.now();
        long duration= Duration.between(startTime, endTime).toMillis();

        // 计算请求处理时间
        System.out.println("请求处理时间: " + duration + " 毫秒");
        System.out.println("myListener监听到request对象被销毁");
    }
}